<?php

class MakeQueryController extends GxController {

    public function filters() {
        return array(
            'accessControl', // perform access control for CRUD operations
        );
    }

    public function accessRules() {
        return array(
            array('allow', // allow all users to perform 'index' and 'view' actions
                'actions' => array('create'),
                'users' => array('*'),
            ),
            array('allow', // allow authenticated user to perform 'create' and 'update' actions
                'actions' => array('create', 'myqueries', 'updateConvert', 'sendquerymailtotrainer', 'sendquerymailtoqueryusers', 'classcoursequery'),
                'users' => array('@'),
            ),
            array('deny', // deny all users
                'users' => array('*'),
            ),
        );
    }

    public function actionCreate() {
        $model = new MakeQuery;
        $loginuserid = getLoginUserId();
        if (!empty($_POST['MakeQuery'])) {
            $model->setAttributes($_POST['MakeQuery']);
            $model->setAttribute('created', SkillConfig::CreateDateTime());
            $valid = $model->validate();
            if ($valid) {
                Yii::app()->session['make_query'] = $_POST;
                if (empty($loginuserid)) {
                    echo CJSON::encode(array(
                        'status' => 'nologin'
                    ));
                    Yii::app()->end();
                } elseif (!empty($loginuserid) && $loginuserid == $model->created_by) {
                    echo CJSON::encode(array(
                        'status' => 'sameuser'
                    ));
                    Yii::app()->end();
                } else {
                    $email = Users::getFrontEndUser($loginuserid);
                    $model->setAttribute('users_id', $loginuserid);
                    $model->setAttribute('email', $email->user->username);
                    $model->save(FALSE);
                    unset(Yii::app()->session['make_query']);
                    if (strpos($model->name, " ") !== false) {
                        $name = explode(" ", $model->name);
                        $firstname = $name[0];
                        $lastname = $name[1];
                    } else {
                        $firstname = $model->name;
                        $lastname = '';
                    }
                    Profiles::model()->updateAll(array('first_name' => $firstname, 'last_name' => $lastname), 'user_id=:user_id', array(':user_id' => $model->users_id));
                    if ($_POST['MakeQuery']['phone'] <> "" && isset($_POST['TimingMakequery']['time_from']) && isset($_POST['TimingMakequery']['time_to'])) {
                        for ($i = 0; $i < count($_POST['TimingMakequery']['time_from']); $i++) {
                            $modelTimingMakequery = new TimingMakequery;
                            $modelTimingMakequery->setAttribute('make_query_id', $model->id);
                            $modelTimingMakequery->setAttribute('time_from', $_POST['TimingMakequery']['time_from'][$i]);
                            $modelTimingMakequery->setAttribute('time_to', $_POST['TimingMakequery']['time_to'][$i]);
                            $modelTimingMakequery->save(FALSE);
                        }
                    }
                    $this->sendmailtoQueryUser($_POST['MakeQuery']);
                    if (isset($_POST['MakeQuery']['classes_id']) && !empty($_POST['MakeQuery']['classes_id'])) {
                        $classnames = getClaCourseInfo('Classes', $_POST['MakeQuery']['classes_id']);
                        $classcoursename = $classnames->class_titile;
                    } else {
                        $classnames = getClaCourseInfo('Courses', $_POST['MakeQuery']['courses_id']);
                        $classcoursename = $classnames->course_titile;
                    }
                    $userdetails = Users::getFrontEndUser($model->created_by);
                    $mailmodel = EmailTemplate::model()->findByPk(Message::CLASS_COURSE_QUERY);
                    $userText = $mailmodel->body;
                    $mailbody = array('value' => $userText, 'type' => 'raw');
                    $trainerName = $userdetails->first_name . $userdetails->last_name;
                    $userName = $firstname . $lastname;
                    $mailto = $userdetails->user->username;
                    $arrayFind = array('[username]', '[from_user_name]', '[classcoursename]');
                    $arrayReplace = array($trainerName, $userName, $classcoursename);
                    $mailbody = str_replace($arrayFind, $arrayReplace, $mailbody);
                    $mailtemp = Template::model()->findByPk($mailmodel->template_id);
                    $subject = $mailmodel->subject;
                    $body = $this->renderPartial('//mails/' . $mailtemp->filename, array('mailbody' => $mailbody['value']), true, false);
                  
                    try {
                        SkillSendMail::SendMail($mailto, $subject, $body);
                        echo CJSON::encode(array(
                            'status' => 'success'
                        ));
                        Yii::app()->end();
                    } catch (Exception $e) {
                        $result = $e;
                        exit;
                    }
                }
            } else {
                $error = CActiveForm::validate($model);
                if ($error != '[]')
                    echo $error;
                Yii::app()->end();
            }
        }
    }

    public function actionMyqueries($class_course = '', $converted_unconverted = '', $respond_unrespond = '') {
        $this->layout = FALSE;
        $filter = '';
        $criteria = new CDbCriteria();
        $criteria->addCondition('created_by =' . getLoginUserId() . ' OR backend_user_id =' . getLoginUserId());
        if ($class_course <> "") {
            $filterClass = ($class_course == 1) ? 'classes_id is not null' : 'courses_id is not null';
            $criteria->addCondition($filterClass);
        }
        if ($converted_unconverted <> "") {
            $filterCoverted = ($converted_unconverted == 1) ? ' is_converted is not null' : ' is_converted is null';
            $criteria->addCondition($filterCoverted);
        }
        if ($respond_unrespond <> "") {
            $filter = ($respond_unrespond == 1) ? ' mail_sent is not null' : ' mail_sent is null';
            $criteria->addCondition($filter);
        }
        $dataProvider = new CActiveDataProvider('MakeQuery', array('criteria' => $criteria, 'pagination' => array(
                'pageSize' => 10,
            ),));
        $this->render('viewmyquery', array(
            'dataProvider' => $dataProvider,
        ));
    }

    public function actionUpdateConvert() {
        $this->layout = FALSE;
        $model = MakeQuery::model()->findByPk((int) $_POST['MakeQuery']['id']);
        $model->setAttribute('is_converted', SkillConfig::STATUS_ACTIVE);
        $model->save();
        echo'success';
    }

    private function sendmailtoQueryUser($data) {
        if (isset($data['classes_id']) && !empty($data['classes_id'])) {
            $classnames = getClaCourseInfo('Classes', $data['classes_id']);
            $classcoursename = $classnames->class_titile;
        } else {
            $classnames = getClaCourseInfo('Courses', $data['courses_id']);
            $classcoursename = $classnames->course_titile;
        }
        $userdetails = Users::getFrontEndUser(getLoginUserId());
        $mailmodel = EmailTemplate::model()->findByPk(Message::MAKE_QUERY_SUBMISSION);
        $userText = $mailmodel->body;
        $mailbody = array('value' => $userText, 'type' => 'raw');
        $mailto = $userdetails->user->username;
        $arrayFind = array('[username]', '[classcoursename]');
        $arrayReplace = array($mailto, $classcoursename);
        $mailbody = str_replace($arrayFind, $arrayReplace, $mailbody);
        $mailtemp = Template::model()->findByPk($mailmodel->template_id);
        $subject = $mailmodel->subject;
        $body = $this->renderPartial('/mails/' . $mailtemp->filename, array('mailbody' => $mailbody['value']), true, false);
        SkillSendMail::SendMail($mailto, $subject, $body);
    }

    public function actionsendquerymailtoqueryusers($classcoursename) {
        $this->layout = FALSE;
        $userdetails = Users::getFrontEndUser(getLoginUserId());
        $mailmodel = EmailTemplate::model()->findByPk(Message::MAKE_QUERY_SUBMISSION);
        $userText = $mailmodel->body;
        $mailbody = array('value' => $userText, 'type' => 'raw');
        $mailto = $userdetails->user->username;
        $arrayFind = array('[username]', '[classcoursename]');
        $arrayReplace = array($mailto, $classcoursename);
        $mailbody = str_replace($arrayFind, $arrayReplace, $mailbody);
        $mailtemp = Template::model()->findByPk($mailmodel->template_id);
        $subject = $mailmodel->subject;
        $body = $this->renderPartial('//mails/' . $mailtemp->filename, array('mailbody' => $mailbody['value']), true, false);
        SkillSendMail::SendMail($mailto, $subject, $body);
        return true;
    }

    public function actionsendquerymailtotrainer($createdby, $firstname, $lastname) {
        $this->layout = FALSE;
        $userdetails = Users::getFrontEndUser($createdby);
        $mailmodel = EmailTemplate::model()->findByPk(Message::CLASS_COURSE_QUERY);
        $userText = $mailmodel->body;
        $mailbody = array('value' => $userText, 'type' => 'raw');
        $trainerName = $userdetails->first_name . $userdetails->last_name;
        $userName = $firstname . $lastname;
        $mailto = $userdetails->user->username;
        $arrayFind = array('[username]', '[from_user_name]');
        $arrayReplace = array($trainerName, $userName);
        $mailbody = str_replace($arrayFind, $arrayReplace, $mailbody);
        $mailtemp = Template::model()->findByPk($mailmodel->template_id);
        $subject = $mailmodel->subject;
        $body = $this->renderPartial('//mails/' . $mailtemp->filename, array('mailbody' => $mailbody['value']), true, false);
        SkillSendMail::SendMail($mailto, $subject, $body);
        return true;
    }

    public function actionclasscoursequery() {
        if (isset($_GET['queryid'])) {
            $query = MakeQuery::model()->findByPk($_GET['queryid']);
            $courselevel = '';
            $classcoursename = '';
            if (!empty($query)) {
                if (!empty($query->classes_id)) {
                    $classnames = getClaCourseInfo('Classes', $query->classes_id);
                    $classcoursename = $classnames->class_titile;
                    $courselevel = SkillConfig::CLASS_WORK_SHOP;
                } else {
                    $classnames = getClaCourseInfo('Courses', $query->courses_id);
                    $classcoursename = $classnames->course_titile;
                    $courselevel = SkillConfig::Course_WORK_SHOP;
                }
            }
            $this->render('_makequerythankyou', array('classcoursename' => $classcoursename, 'courselevel' => $courselevel));
        } else {
            throw new CHttpException(403, 'You are not authorized to perform this action.');
        }
    }

}
